/**
 * Created by yangxianming on 2015-04-30.
 */

import com.alibaba.fastjson.JSONObject;
import models.GetRequestInputStream;
import models.MyConfig;
import models.ReturnJson;
import tools.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

// 扩展 HttpServlet 类
@WebServlet(name = "test2", urlPatterns = {"/test2"}, loadOnStartup = 2)
public class Test2 extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    Properties properties;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        this.properties = readProperties.getProperties();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        {"name":"","age":""}
        PrintWriter out = resp.getWriter();
        JSONObject requestInfo = GetRequestInputStream.getJson(req);
        System.out.println("name:" + requestInfo.getString("name"));
        System.out.println("age:" + requestInfo.getString("age"));
        ReturnJson returnJson = new ReturnJson();
        returnJson.setResult("return success");
        returnJson.setApiStatus(1);
        out.print(returnJson.toString());

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long start = new Date().getTime();
        PrintWriter out = response.getWriter();
        String string = "";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf1.format(new Date());

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        String fromIp = request.getRemoteAddr();
        try {
            string = new String(request.getParameter("string").getBytes(),"UTF-8");
        }catch (NullPointerException e){
            string = "?string=null . we need string";
        }
        System.out.println("ip:" + fromIp);
        System.out.println("string:" + string);

        out.print(string);

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

    }

    public void destroy()
    {
        // 什么也不做
    }

}